/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmLogin.java
 *
 * Created on 07-jun-2012, 12:01:26
 */
package Codigo;

import java.io.*;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;

/**
 *
 * @author Kyerte
 */
public class FrmLogin extends javax.swing.JFrame {

    String user = "";
    String pass = "";
    String server = "";
    String base = "";
    String puerto = "";
    String usuario = "";
    String password = "";
    String ruta;
    static final String CONTROLADOR = "com.mysql.jdbc.Driver";
    File archivoConf;
    public static Connection conexion;
    private PreparedStatement buscarUsuario = null;
    private boolean admin;

    /**
     * Creates new form frmLogin
     */
    public FrmLogin(String rutaApp) {

//        try {
//
//            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//
//        } catch (Exception e) {
//
//            e.printStackTrace();
//        }

        ruta = rutaApp;

        initComponents();
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagenes/Security.png")).getImage());

        verificarAchivoConf();
        conectarBD();

    }

    private void verificarAchivoConf() {

        archivoConf = new File(ruta, "Eggo.conf");

        if (!archivoConf.exists()) {

            try {

                System.out.println(archivoConf.createNewFile());

                JOptionPane.showMessageDialog(null, "Ingresa los datos de "
                        + "conexión a la base de datos", "Incapacidades",
                        JOptionPane.WARNING_MESSAGE);

                escribirArchivo();
                leerArchivo();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else {
            leerArchivo();
        }
    }

    private void escribirArchivo() {

        FileWriter escritor;
        BufferedWriter bufer;
        PrintWriter escribir;

        JTextField txtNewUser = new JTextField();
        JTextField txtNewPass = new JTextField();
        JTextField txtServidor = new JTextField();
        JTextField txtPuerto = new JTextField();
        JTextField txtBD = new JTextField();

        String userCon;
        String passCon;
        String serverCon;
        String port;
        String db;

        Object[] controles = {"Usuario", txtNewUser, "Contraseña", txtNewPass,
            "Servidor", txtServidor, "Puerto", txtPuerto, "Base de datos", txtBD};

        int opc = JOptionPane.showConfirmDialog(null, controles,
                "Conexión a base de datos",
                JOptionPane.OK_CANCEL_OPTION);

        if (opc == 0) {

            userCon = txtNewUser.getText();
            passCon = txtNewPass.getText();
            serverCon = txtServidor.getText();
            port = txtPuerto.getText();
            db = txtBD.getText();

            try {

                escritor = new FileWriter(archivoConf);
                bufer = new BufferedWriter(escritor);
                escribir = new PrintWriter(bufer);

                escribir.write(userCon + "\n" + passCon + "\n" + serverCon + "\n" + port + "\n" + db);
                escribir.close();

            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Error al escribir en el archivo",
                        "Incapacidades", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            System.exit(0);
        }
    }

    private void conectarBD() {
        try {

            conexion = DriverManager.getConnection("jdbc:mysql://" + server + ":" + puerto
                    + "/" + base, user, pass);

            Class.forName(CONTROLADOR);

            if (conexion != null) {
                System.out.println("Conexión Establecida");
            } else {
                System.out.println("Conexión No Establecida");
            }

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FrmLogin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {

            JOptionPane.showMessageDialog(null, "No se pudo conectar a la base de datos \n"
                    + "Ingresa la información", "Error de conexión", JOptionPane.ERROR_MESSAGE);

            escribirArchivo();
            leerArchivo();
            conectarBD();
        }

        try {

            buscarUsuario = conexion.prepareStatement("SELECT * FROM Usuarios WHERE "
                    + "Usuario = ? AND Password = ?");

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    private boolean buscarLogin() {

        ResultSet conjuntoResultados = null;
        boolean existe = false;
        int contador = 0;

        try {

            buscarUsuario.setString(1, usuario);
            buscarUsuario.setString(2, password);
            conjuntoResultados = buscarUsuario.executeQuery();

            while (conjuntoResultados.next()) {
                contador++;
                admin = conjuntoResultados.getBoolean("Tipo");
            }

            if (contador > 0) {
                existe = true;
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return existe;
    }

    private void ingresar() {

        usuario = txt_Usuario.getText();
        password = txt_Contrasena.getText();

        if (!usuario.isEmpty() && !password.isEmpty()) {
            if (buscarLogin()) {
                FrmPrincipal ventana = new FrmPrincipal(usuario, conexion, admin);
                ventana.setLocationRelativeTo(null);
                ventana.setVisible(true);
                dispose();
            } else {
                JOptionPane.showMessageDialog(null, "Error de usuario/contaseña", "Login",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Ingresa usuario y contraseña",
                    "Error de ingreso", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblUsuario = new javax.swing.JLabel();
        lblContrasena = new javax.swing.JLabel();
        txt_Usuario = new javax.swing.JTextField();
        txt_Contrasena = new javax.swing.JPasswordField();
        lblImg = new javax.swing.JLabel();
        cmd_Aceptar = new javax.swing.JButton();
        cmd_Cancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(153, 153, 153));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos de acceso"));
        jPanel1.setName("jPanel1"); // NOI18N

        lblUsuario.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblUsuario.setText("Usuario");
        lblUsuario.setName("lblUsuario"); // NOI18N

        lblContrasena.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblContrasena.setText("Contraseña");
        lblContrasena.setName("lblContrasena"); // NOI18N

        txt_Usuario.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txt_Usuario.setName("txt_Usuario"); // NOI18N
        txt_Usuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_UsuarioActionPerformed(evt);
            }
        });

        txt_Contrasena.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txt_Contrasena.setName("txt_Contrasena"); // NOI18N
        txt_Contrasena.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_ContrasenaActionPerformed(evt);
            }
        });

        lblImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Security.png"))); // NOI18N
        lblImg.setName("lblImg"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblImg)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblContrasena)
                    .addComponent(lblUsuario))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txt_Contrasena, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                    .addComponent(txt_Usuario, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txt_Usuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblUsuario))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txt_Contrasena)
                            .addComponent(lblContrasena)))
                    .addComponent(lblImg))
                .addContainerGap())
        );

        cmd_Aceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/LogOff.png"))); // NOI18N
        cmd_Aceptar.setMnemonic('A');
        cmd_Aceptar.setText("Aceptar");
        cmd_Aceptar.setName("cmd_Aceptar"); // NOI18N
        cmd_Aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmd_AceptarActionPerformed(evt);
            }
        });

        cmd_Cancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Shutdown.png"))); // NOI18N
        cmd_Cancelar.setMnemonic('C');
        cmd_Cancelar.setText("Cancelar");
        cmd_Cancelar.setName("cmd_Cancelar"); // NOI18N
        cmd_Cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmd_CancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cmd_Aceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cmd_Cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmd_Aceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmd_Cancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void cmd_AceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmd_AceptarActionPerformed
// TODO add your handling code here:
    ingresar();
}//GEN-LAST:event_cmd_AceptarActionPerformed

private void cmd_CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmd_CancelarActionPerformed
// TODO add your handling code here:
    System.exit(0);
}//GEN-LAST:event_cmd_CancelarActionPerformed

private void txt_ContrasenaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_ContrasenaActionPerformed
// TODO add your handling code here:
    ingresar();
}//GEN-LAST:event_txt_ContrasenaActionPerformed

    private void txt_UsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_UsuarioActionPerformed
        txt_Contrasena.requestFocus();
    }//GEN-LAST:event_txt_UsuarioActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmd_Aceptar;
    private javax.swing.JButton cmd_Cancelar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblContrasena;
    private javax.swing.JLabel lblImg;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JPasswordField txt_Contrasena;
    private javax.swing.JTextField txt_Usuario;
    // End of variables declaration//GEN-END:variables

    private void leerArchivo() {
        FileReader fr = null;
        BufferedReader br = null;

        try {
            fr = new FileReader(archivoConf);
            br = new BufferedReader(fr);

            // Lectura del fichero            
            user = br.readLine();
            pass = br.readLine();
            server = br.readLine();
            puerto = br.readLine();
            base = br.readLine();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fr) {
                    fr.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}
